package modelo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import hbt.AbstractHibernateManager;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import entities.DepositoEntity;
import entities.DepositoEntity;
import entities.SucursalEntity;

public class DepositoDao extends AbstractHibernateManager {	
	
	private static DepositoDao instancia = null;
	
	public static DepositoDao getInstancia() {
		if(instancia == null) {
			instancia = new DepositoDao();
		}
		return instancia;
	}
		
	
	public void save(DepositoEntity depo){
		Session s= null;
		try {
			s=getNewSession();
			s.beginTransaction();
			s.persist(depo);
			s.flush();
			s.getTransaction().commit();
			System.out.println("[deposito PERSISTED ON TABLE depositos]::OK");
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			closeSession(s);
		}
	}
	
	
	public void guardar(DepositoEntity depo){
		Session s= null;
		try {
			s=getNewSession();
			s.beginTransaction();
			s.save(depo);
			s.flush();
			s.getTransaction().commit();
			System.out.println("[deposito SAVED ON TABLE depositos]::OK");
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			closeSession(s);
		}
	}

	
	public DepositoEntity obtenerDeposito(Integer id) {
		Session s = null;
		DepositoEntity deposito = new DepositoEntity();
		
		try {
			s = getNewSession();
			deposito =  (DepositoEntity) s.createQuery("FROM DepositoEntity depo " +
									"WHERE depo.id = :idDepo")
							  .setInteger("idDepo", id)
							  .uniqueResult();
			System.out.println("\nTipo Deposito: "+deposito.getTipo());
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally{
			closeSession(s);
		}
		return deposito;
	}
	
	public List<DepositoEntity> obtenerDepositos() {
		Session s = null;
		List<DepositoEntity> lista = new ArrayList<DepositoEntity>();
		try {
			s = getNewSession();
			@SuppressWarnings("rawtypes")
			Iterator iLista = s.createQuery("FROM DepositoEntity depo").iterate();
			while(iLista.hasNext()) {
				DepositoEntity enti = (DepositoEntity) iLista.next();
				lista.add(enti);
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally{
			closeSession(s);
		}
		return lista;
	}
}
